<template>
  <div style="margin-top: 50px">
<el-dialog title="新增商品规格" :visible.sync="dialogFormVisible">

        <el-form :inline="true" :model="AddFormData" :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <el-form-item label="规格名称" prop="PropertiesName">
        <el-input class="ggmc" v-model="AddFormData.PropertiesName"></el-input>
      </el-form-item>
      <el-form-item label="售价" prop="minPrice">
        <el-input class="sj" v-model.number="AddFormData.minPrice"></el-input>
      </el-form-item>
      <el-form-item label="市场价" prop="originalPrice">
        <el-input class="scj" v-model.number="AddFormData.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="stores">
        <el-input class="kc" v-model.number="AddFormData.stores"></el-input>
      </el-form-item>
      <div>
      <el-form-item class="anniu">
        <el-button @click="qx_AddProductProperties('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="tj_AddProductProperties('ruleForm')">立即创建</el-button>
      </el-form-item>
      </div>
        </el-form>
  
</el-dialog>
    <el-form :model="value" ref="productAttrForm" label-width="120px" style="width: 720px" size="small">
      <el-form-item label="商品规格：">
        <el-button class="littleMarginLeft" @click="dialogFormVisible = true">新增</el-button>
        <el-table style="width: 100%;margin-top: 20px"
                  :data="value.properties_data"
                  border>
          <el-table-column
            label="规格名称"
            align="center">
            <template slot-scope="scope">
              {{scope.row.PropertiesName}}
            </template>
          </el-table-column>
          <el-table-column
            label="售价"
            width="80"
            align="center">
            <template slot-scope="scope">
              {{scope.row.minPrice}}
            </template>
          </el-table-column>
          <el-table-column
            label="原价"
            width="80"
            align="center">
            <template slot-scope="scope">
              {{scope.row.originalPrice}}
            </template>
          </el-table-column>
          <el-table-column
            label="库存"
            width="80"
            align="center">
            <template slot-scope="scope">
              {{scope.row.stores}}
            </template>
          </el-table-column>
          <el-table-column
            label="默认选择"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-switch
                @change="PropertiesActiveChange(scope.$index, scope.row)"
                :active-value="true"
                :inactive-value="false"
                v-model="scope.row.active">
              </el-switch>

            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleRemoveProperties(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="商品主图：">
        <multi-upload v-model="selectProductPics" :leibie="'zt'"></multi-upload>
      </el-form-item>
      <el-form-item label="商品轮播图：">
        <multi-upload v-model="selectProductLbtPics" :maxCount='5' :leibie="'lbt'"></multi-upload>
      </el-form-item>
      <el-form-item label="小程序端详情：">
            <tinymce :width="595" :height="600"  type="card" v-model="value.detailMobileHtml"></tinymce>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev">上一步，填写商品信息</el-button>
        <el-button type="primary" size="medium" @click="handleNext">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {fetchList as fetchProductAttrCateList} from '@/api/productAttrCate'
  import {GoodsProperties} from '@/api/productCate'
  import {fetchList as fetchProductAttrList} from '@/api/productAttr'
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import Tinymce from '@/components/Tinymce'

  export default {
    name: "ProductAttrDetail",
    components: {SingleUpload, MultiUpload, Tinymce},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        dialogFormVisible: false,
        //编辑模式时是否初始化成功
        hasEditCreated:false,
        //商品属性分类下拉选项
        productAttributeCategoryOptions: [],
        //当前商品的规格列表
        goodsPropertiesList:[],
        //选中的商品属性
        selectProductAttr: [],
        //选中的商品参数
        selectProductParam: [],
        //选中的商品属性图片
        selectProductAttrPics: [],
        //可手动添加的商品属性
        addProductAttrValue: '',
        //商品富文本详情激活类型
        activeHtmlName: 'pc',
        AddFormData:{
          PropertiesName:'',
          active:false,
          minPrice:'',
          originalPrice:'',
          stores:''
        },
        rules: {
          PropertiesName: [
            { required: true, message: '请输入规格名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          minPrice: [
            { required: true, message: '请输入售价', trigger: 'blur' },
            { type: 'number', message: '必须为数字值', trigger: 'blur' },
          ],
          originalPrice: [
            { required: true, message: '请输入原价', trigger: 'blur' },
            { type: 'number', message: '必须为数字值', trigger: 'blur' },
          ],
          stores: [
            { required: true, message: '请示输入库存', trigger: 'blur' },
            { type: 'number', message: '必须为数字值', trigger: 'blur' },
          ],
        }
      }
    },
    computed: {
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          console.log('执行主图，get方法')
          let pics=[];
          if(this.value.pic===undefined||this.value.pic==null||this.value.pic===''){
            return pics;
          }
          pics.push(this.value.pic);
          if(this.value.albumPics===undefined||this.value.albumPics==null||this.value.albumPics===''){
            return pics;
          }
          let albumPics = this.value.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.pic = null;
            this.value.albumPics = null;
          } else {
            this.value.pic = newValue[0];
            this.value.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumPics += ',';
                }
              }
            }
          }
        }
      },
      //商品的轮播图
      selectProductLbtPics:{
        get:function () {
          if(this.value.lbt===undefined||this.value.lbt==null||this.value.lbt===''){
            return
          }
          let lbt = this.value.lbt;
          let pics=[];
          for(let i=0;i<lbt.length;i++){
            pics.push(lbt[i].pic);
          }
          return pics;
        },
        set:function (newValue) {
          if(newValue===undefined||newValue==null||newValue===''){
            this.value.lbt = []
            return
          }
          let lbt = [];
          for(let i=0;i<newValue.length;i++){
            lbt.push({pic:newValue[i]});
          }
          this.value.lbt = lbt
          console.log(lbt)
        }
      }
    },
    created() {
      // this.getProductAttrCateList();
    },

    methods: {
      qx_AddProductProperties(name){
          this.AddFormData = {
            PropertiesName:'',
            active:false,
            minPrice:'',
            originalPrice:'',
            stores:''
            }
  
          this.$refs[name].resetFields();
      
          this.dialogFormVisible = false
      },
      //添加商品规格
      tj_AddProductProperties(name){
         this.$refs[name].validate((valid) => {
          if (valid) {
            this.value.properties_data.push(this.AddFormData)
            this.AddFormData = {
            PropertiesName:'',
            active:false,
            minPrice:'',
            originalPrice:'',
            stores:''
            }
          this.dialogFormVisible = false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      
      //删除商品规格
      handleRemoveProperties(index, data){
        this.value.properties_data.splice(index,1); 
      },

      // 设置默认选择的商品规格
      PropertiesActiveChange(index, data){
        console.log(index,data)
        if(!data.active){
          this.$message.error('不能取消，应至少保证一项默认规格！您可选择其他规格，该项自动取消。');
          this.value.properties_data[index].active = true
          return
        }
        for (let i = 0; i < this.value.properties_data.length; i++) {
            this.value.properties_data[i].active = false
          }
            this.value.properties_data[index].active = true
      },

      
      handleEditCreated() {
        //根据商品属性分类id获取属性和参数
        if(this.value.productAttributeCategoryId!=null){
          this.handleProductAttrChange(this.value.productAttributeCategoryId);
        }
        this.hasEditCreated=true;
      },
      getProductAttrCateList() {
        let param = {pageNum: 1, pageSize: 100};
        fetchProductAttrCateList(param).then(response => {
          this.productAttributeCategoryOptions = [];
          let list = response.data.list;
          for (let i = 0; i < list.length; i++) {
            this.productAttributeCategoryOptions.push({label: list[i].name, value: list[i].id});
          }
        });
      },
      getProductAttrList(type, cid) {
        let param = {pageNum: 1, pageSize: 100, type: type};
        fetchProductAttrList(cid, param).then(response => {
          let list = response.data.list;
          if (type === 0) {
            this.selectProductAttr = [];
            for (let i = 0; i < list.length; i++) {
              let options = [];
              let values = [];
              if (this.isEdit) {
                if (list[i].handAddStatus === 1) {
                  //编辑状态下获取手动添加编辑属性
                  options = this.getEditAttrOptions(list[i].id);
                }
                //编辑状态下获取选中属性
                values = this.getEditAttrValues(i);
              }
              this.selectProductAttr.push({
                id: list[i].id,
                name: list[i].name,
                handAddStatus: list[i].handAddStatus,
                inputList: list[i].inputList,
                values: values,
                options: options
              });
            }
            if(this.isEdit){
              //编辑模式下刷新商品属性图片
              this.refreshProductAttrPics();
            }
          } else {
            this.selectProductParam = [];
            for (let i = 0; i < list.length; i++) {
              let value=null;
              if(this.isEdit){
                //编辑模式下获取参数属性
                value= this.getEditParamValue(list[i].id);
              }
              this.selectProductParam.push({
                id: list[i].id,
                name: list[i].name,
                value: value,
                inputType: list[i].inputType,
                inputList: list[i].inputList
              });
            }
          }
        });
      },
      //获取设置的可手动添加属性值
      getEditAttrOptions(id) {
        let options = [];
        for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
          let attrValue = this.value.productAttributeValueList[i];
          if (attrValue.productAttributeId === id) {
            let strArr = attrValue.value.split(',');
            for (let j = 0; j < strArr.length; j++) {
              options.push(strArr[j]);
            }
            break;
          }
        }
        return options;
      },
      //获取选中的属性值
      getEditAttrValues(index) {
        let values = [];
        if (index === 0) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp1 != null && values.indexOf(sku.sp1) === -1) {
              values.push(sku.sp1);
            }
          }
        } else if (index === 1) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp2 != null && values.indexOf(sku.sp2) === -1) {
              values.push(sku.sp2);
            }
          }
        } else {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp3 != null && values.indexOf(sku.sp3) === -1) {
              values.push(sku.sp3);
            }
          }
        }
        return values;
      },
      //获取属性的值
      getEditParamValue(id){
        for(let i=0;i<this.value.productAttributeValueList.length;i++){
          if(id===this.value.productAttributeValueList[i].productAttributeId){
            return this.value.productAttributeValueList[i].value;
          }
        }
      },
      getInputListArr(inputList) {
        return inputList.split(',');
      },
      handleAddProductAttrValue(idx) {
        let options = this.selectProductAttr[idx].options;
        if (this.addProductAttrValue == null || this.addProductAttrValue == '') {
          this.$message({
            message: '属性值不能为空',
            type: 'warning',
            duration: 1000
          });
          return
        }
        if (options.indexOf(this.addProductAttrValue) !== -1) {
          this.$message({
            message: '属性值不能重复',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.selectProductAttr[idx].options.push(this.addProductAttrValue);
        this.addProductAttrValue = null;
      },
      handleRemoveProductAttrValue(idx, index) {
        this.selectProductAttr[idx].options.splice(index, 1);
      },
      
      refreshProductAttrPics() {
        this.selectProductAttrPics = [];
        if (this.selectProductAttr.length >= 1) {
          let values = this.selectProductAttr[0].values;
          for (let i = 0; i < values.length; i++) {
            let pic=null;
            if(this.isEdit){
              //编辑状态下获取图片
              pic=this.getProductSkuPic(values[i]);
            }
            this.selectProductAttrPics.push({name: values[i], pic: pic})
          }
        }
      },
      //获取商品相关属性的图片
      getProductSkuPic(name){
        for(let i=0;i<this.value.skuStockList.length;i++){
          if(name===this.value.skuStockList[i].sp1){
            return this.value.skuStockList[i].pic;
          }
        }
        return null;
      },
      getOptionStr(arr) {
        let str = '';
        for (let i = 0; i < arr.length; i++) {
          str += arr[i];
          if (i != arr.length - 1) {
            str += ',';
          }
        }
        return str;
      },
      handleRemoveProductSku(index, row) {
        let list = this.value.skuStockList;
        if (list.length === 1) {
          list.pop();
        } else {
          list.splice(index, 1);
        }
      },
      getParamInputList(inputList) {
        return inputList.split(',');
      },
      handlePrev() {
        this.$emit('prevStep')
      },
      handleNext() {
        if(Array.isArray(this.value.properties_data) && this.value.properties_data.length === 0){
          this.$message({
              message: '请添加商品规格！',
              type: 'error',
              duration:1000
            });
            return
        }
        if(!this.value.pic){
          this.$message({
              message: '请上传商品主图！',
              type: 'error',
              duration:1000
            });
            return
        }
        if(Array.isArray(this.value.lbt) && this.value.lbt.length === 0){
          this.$message({
              message: '请上传商品轮播图！',
              type: 'error',
              duration:1000
            });
            return
        }
        if(!this.value.detailMobileHtml){
          this.$message({
              message: '请填写商品详情！',
              type: 'error',
              duration:1000
            });
            return
        }
        this.$emit('nextStep')
      }
    }
  }
</script>

<style scoped>
  .littleMarginLeft {
    margin-left: 10px;
  }

  .littleMarginTop {
    margin-top: 10px;
  }

  .paramInput {
    width: 250px;
  }

  .paramInputLabel {
    display: inline-block;
    width: 100px;
    text-align: right;
    padding-right: 10px
  }

  .cardBg {
    background: #F8F9FC;
  }

  .ggmc{
    width: 260px;
  }

  .sj,.scj,.kc{
    width: 100px;
  }

  .anniu{
    display: block;
    padding-top: 20px;
    margin: 0;
    padding-left: 20px;
  }
</style>
